package com.zg.sso.util;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisSentinelPool;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Component
@Configuration
public class ZtRedisUtil {

    @Value("${zt.redis.redisUrl}")
    private String redisUrl;
    @Value("${zt.redis.password}")
    private String password;
    @Value("${zt.redis.database}")
    private int database;

    private static JedisSentinelPool pool;

    /**
     * 初始化Redis连接池
     */
    private void initPool() {
        if (pool == null) {
            synchronized (ZtRedisUtil.class) {
                if (pool == null) {
                    try {
                        String[] hostArray = redisUrl.split(",");
                        Set<String> sentinels = new HashSet<>();
                        for (int i = 0; i < hostArray.length; i++) {
                            sentinels.add(hostArray[i]);
                        }
                        pool = new JedisSentinelPool("mymaster", sentinels, new GenericObjectPoolConfig(), 1000, password, database);
                    } catch (Exception e) {
                        throw new RuntimeException("Redis连接池初始化失败", e);
                    }
                }
            }
        }
    }

    /**
     * 获取Jedis实例
     */
    private Jedis getJedis() {
        if (pool == null) {
            initPool();
        }
        return pool.getResource();
    }

    /**
     * 获取redis中指定key的值，value类型为String的使用此方法
     */
    public String get(String key) {
        try (Jedis jedis = getJedis()) {
            return jedis.get(key);
        }
    }

    /**
     * 设置redis中指定key的值，value类型为String的使用此方法
     */
    public void set(String key, String value) {
        try (Jedis jedis = getJedis()) {
            jedis.set(key, value);
        }
    }

    /**
     * 获取redis中指定key的值,对应的value，value类型为MAP的使用此方法
     */
    public Map<String, String> getMap(String key) {
        try (Jedis jedis = getJedis()) {
            return jedis.hgetAll(key);
        }
    }

    /**
     * 删除redis中指定key的值项
     */
    public void del(String key) {
        try (Jedis jedis = getJedis()) {
            jedis.del(key);
        }
    }

    /**
     * 为指定key设置过期时间（秒）
     * @param key 键名
     * @param seconds 过期时间（秒）
     * @return 成功返回1，失败返回0
     */
    public Long expire(String key, int seconds) {
        try (Jedis jedis = getJedis()) {
            return jedis.expire(key, seconds);
        }
    }

    /**
     * 关闭连接池
     */
    public void close() {
        if (pool != null && !pool.isClosed()) {
            pool.close();
        }
    }
}
